<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/15 0015
 * Time: 15:20
 */

namespace common\models\PercentageItem;


use common\components\DataHelper;
use common\models\Admin\Admin;
use common\models\AgentInfo\AgentInfo;
use common\models\Percentage\Percentage;
use common\models\PlugsRunTotal\PlugsRunTotal;
use common\models\RegionManagerInfo\RegionManagerInfo;
use yii\db\ActiveQuery;

class PercentageItem extends PercentageItemBase
{
    public function getYesterdayData()
    {
        return $this->hasOne(self::class, [
            "plug_id" => "plug_id",
            "manager_id" => "manager_id",
            "agent_id" => "agent_id",
        ])->andWhere([
            "created_date" => date("Y-m-d", strtotime("-1 day")),
        ]);
    }

    public function getYesterdayAgentNum()
    {
        return $this->hasOne(self::class, [
            "agent_id" => "agent_id",
        ])->andWhere([
            "created_date" => date("Y-m-d", strtotime("-1 day")),
            "parent_agent" => 0
        ])->groupBy("agent_id")->select([
            "agent_id",
            "sum(upper_num) as terminal_num",
        ]);
    }

    public function getYesterdayManagerNum()
    {
        return $this->hasOne(self::class, [
            "manager_id" => "manager_id",
        ])->andWhere([
            "created_date" => date("Y-m-d", strtotime("-1 day")),
            "parent_agent" => 0
        ])->groupBy("manager_id")->select([
            "manager_id",
            "sum(upper_num) as terminal_num",
        ]);;
    }

    /**
     * 创建检索条件
     * @param ActiveQuery $query
     * @param $params
     */
    public static function createSearchCondition(ActiveQuery $query, $params)
    {

        if ( @$params["key"] ) {
            switch ( $params["key"] ) {
                case  "agent_uid":
                    $params["agent_uid"] = @$params["val"];
                    break;
                case "agent_account";
                    $params["agent_account"] = @$params["val"];
                    break;
                case "agent_name":
                    $params["agent_name"] = @$params["val"];
                    break;
                case "manager_name":
                    $params["manager_name"] = @$params["val"];
                    break;
            }
        }

        if ( @$params["agent_id"] ) {
            $query->andWhere([
                "agent_id" => $params["agent_id"]
            ]);
        }
        if ( @$params["agent_uid"] ) {
            $query->andWhere([
                "agent_id" => $params["agent_uid"]
            ]);
        }

        if ( @$params["agent_account"] ) {
            $agentIds = Admin::find()->select("id")->where([
                "type" => Admin::TYPE_AGENT
            ])->andWhere([
                "like",
                "username",
                $params["agent_account"]
            ])->asArray()->all();
            $query->andWhere([
                "agent_id" => array_column($agentIds, "id")
            ]);
        }

        if ( @$params["agent_name"] ) {
            $agentIds = AgentInfo::find()->select("uid")->andWhere([
                "like",
                "name",
                $params["agent_name"]
            ])->asArray()->all();
            $query->andWhere([
                "agent_id" => array_column($agentIds, "uid")
            ]);
        }

        if ( @$params["manager_name"] ) {
            $agentIds = RegionManagerInfo::find()->select("uid")->andWhere([
                "like",
                "name",
                $params["manager_name"]
            ])->asArray()->all();
            $query->andWhere([
                "manager_id" => array_column($agentIds, "uid")
            ]);
        }

        if ( @$params["manager_id"] ) {
            $query->andWhere([
                "manager_id" => $params["manager_id"]
            ]);
        }

        if ( @$params["agent_status"] ) {
            $query->andWhere([
                "agent_status" => $params["agent_status"]
            ]);
        }
        if ( @$params["manager_status"] ) {
            $query->andWhere([
                "manager_status" => $params["manager_status"]
            ]);
        }
        if ( @$params["manager_uid"] ) {
            $query->andWhere([
                "manager_id" => $params["manager_uid"]
            ]);
        }

        if ( @$params["time_start"] ) {
            $query->andWhere("created_date >= :start", [
                ":start" => $params["time_start"]
            ]);
        }

        if ( @$params["time_end"] ) {
            $query->andWhere("created_date <= :end", [
                ":end" => $params["time_end"]
            ]);
        }

        if ( @$params["created_date"] ) {
            $query->andWhere([
                "created_date" => $params["created_date"]
            ]);
        }

        if ( @$params["created_ym"] ) {
            $query->andWhere("created_ym = :created_ym", [
                ":created_ym" => $params["created_ym"]
            ]);
        }

        return ;
    }

    public static function set(Percentage $percentage, $isView = false)
    {
        if ( $percentage->status == Percentage::STATUS_YES ) {
            self::error("该记录已分成");
            return false;
        }

        //获取对应的终端上报数据
        $plugsRunTotal = PlugsRunTotal::find()->where([
            "plug_id" => $percentage->plug_id,
            "created_date" => $percentage->created_date
        ])->with(["agentInfo", "managerInfo"])->all();
        $paramsKeyTop = "top";
        $paramsKeyChildren = "children";
        $params = [
            $paramsKeyTop => [],//顶级代理
            $paramsKeyChildren => []//子集代理
        ];
        $createdTime = DataHelper::date();
        $ym = date("Y-m", strtotime($percentage->created_date));
        foreach ( $plugsRunTotal as $item ) {
            $upper_num = round($item->terminal_num * $percentage->getNumRate(), 0);
            $key = $item->agentInfo["parent_agent"] > 0 ? $paramsKeyChildren : $paramsKeyTop;
            $params[$key][$item->agent_uid . "_" . $item->manager_uid] = [
                "percentage_id" => $percentage->id,
                "agent_id" => $item->agent_uid,
                "manager_id" => $item->manager_uid,
                "real_num" => $item->terminal_num,
                "upper_num" => $upper_num,
                "self_real_num" => $item->terminal_num,
                "self_upper_num" => $upper_num,
                "created_date" => $percentage->created_date,
                "updated_time" => $createdTime,
                "agent_name" => $item->agentInfo["name"],
                "manager_name" => $item->managerInfo["name"],
                "created_ym" => $ym,
                "province" => $item->province,
                "city" => $item->city,
                "plug_id" => $percentage->plug_id,
                "parent_agent" => $item->agentInfo["parent_agent"]
            ];
        }

        //累计上顶级代理的终端数【把下级代理的终端数加入上级代理】
        foreach ( $params[$paramsKeyChildren] as $childrenItem ) {
            $key = $childrenItem["parent_agent"] . "_" . $childrenItem["manager_id"];
            if ( isset($params[$paramsKeyTop][$key]) ) {
                $params[$paramsKeyTop][$key]["real_num"] += $childrenItem["real_num"];
                $params[$paramsKeyTop][$key]["upper_num"] += $childrenItem["upper_num"];
            } else {
                $agentInfo = AgentInfo::findOne([
                    "uid" => $childrenItem["parent_agent"]
                ]);
                if ( $agentInfo ) {
                    $params[$paramsKeyTop][$key] = $childrenItem;
                    $params[$paramsKeyTop][$key]["parent_agent"] = 0;
                    $params[$paramsKeyTop][$key]["agent_id"] = $childrenItem["parent_agent"];
                    $params[$paramsKeyTop][$key]["agent_name"] = $agentInfo->name;
                }
            }
        }

        //预览则直接 预览只显示top return
        if ( $isView ) {
            return $params[$paramsKeyTop];
        }

        $self = new self();
        $transaction = $self::getDb()->beginTransaction();
        foreach ( $params as $item ) {
            foreach ( $item as $attributes ) {
                $self->attributes = $attributes;
                $self->parent_agent = intval($self->parent_agent);
                $self->agent_status = self::STATUS_NO;
                $self->manager_status = self::STATUS_NO;
                $self->id = null;
                $self->isNewRecord = true;
                //如果这条数据插入失败则回滚数据
                if ( !$self->insert(0) ) {
                    $transaction->rollBack();
                    self::error("系统繁忙，分成失败");
                    return false;
                }
            }
        }
        $percentage->status = Percentage::STATUS_YES;
        if ( !$percentage->update(0) ) {
            self::error("数据更新失败");
            return false;
        }
        $transaction->commit();
        return $params;
    }



    public function getAgentInfo()
    {
        return $this->hasOne(AgentInfo::class, [
            "uid" => "agent_id",
        ]);
    }

    public function getManagerInfo()
    {
        return $this->hasOne(RegionManagerInfo::class, [
            "uid" => "manager_id",
        ]);
    }
    public function getPercentage()
    {
        return $this->hasOne(Percentage::class, [
            "id" => "percentage_id"
        ]);
    }
}